#include "freertos.h"
#include "task.h"
#include "semphr.h"
//#include "malloc.h"
#include "fsl_debug_console.h"

#include "key.h"

extern SemaphoreHandle_t xSemaphore_pre;
extern SemaphoreHandle_t xSemaphore_next;
extern SemaphoreHandle_t xSemaphore_ok;

//任务优先级
#define TASK_KEY_TASK_PRIO		(configMAX_PRIORITIES-2)
//任务堆栈大小
#define TASK_KEY_STK_SIZE 		128
//任务堆栈
StackType_t task_key_stack[TASK_KEY_STK_SIZE];
//任务控制块
StaticTask_t task_key_tcb;
//任务句柄
TaskHandle_t task_key_handler;
//任务函数
void task_key(void *pvParameters)
{
//	uint16_t percent1, percent2;
	uint8_t key = 0;
	uint8_t oldkey = 0;
	while (1)
	{
		vTaskDelay(20);
		key = KEY_Scan();
		if (key == 0)
		{
			oldkey = 0;
			continue;
		}

		if (oldkey == key)
		{
			continue;
		}

		switch (key)
		{
		case KEY_NEXT_PRES:
			if (xSemaphore_next != NULL)
			{
				xSemaphoreGive(xSemaphore_next);
			}
			break;
		case KEY_OK_PRES:
			if (xSemaphore_ok != NULL)
			{
				xSemaphoreGive(xSemaphore_ok);
			}
			break;
		case KEY_PRE_PRES:
			if (xSemaphore_pre != NULL)
			{
				xSemaphoreGive(xSemaphore_pre);
			}
			break;
		default:
			break;
		}

		oldkey = key;
		PRINTF("key pressed %d!\n", oldkey);

	}
}


void task_key_init(void)
{
	task_key_handler = xTaskCreateStatic((TaskFunction_t)task_key,
										 (const char *)"task_key",
										 (uint32_t)TASK_KEY_STK_SIZE,
										 (void *)NULL,
										 (UBaseType_t)TASK_KEY_TASK_PRIO,
										 (StackType_t *)task_key_stack,
										 (StaticTask_t *)&task_key_tcb);
}
